package models

import (
	"fmt"
	"gin_template/core/redis"
	timeConst "gin_template/data/time"
	"time"

	"go.uber.org/zap"
)

type TokenFormat struct {
	Signature string `json:"signature,omitempty"`
	Timestamp string `json:"timestamp,omitempty"`
	Nonce     string `json:"nonce,omitempty"`
	Echostr   string `json:"echostr,omitempty"`
}

type RemindJobInfo struct {
	TimeNum      string `json:"timeNum,omitempty" `
	TimeUnitByMs string `json:"timeUnitByMs,omitempty" `
	RemindTask   string `json:"remindTask,omitempty" `
	RemindUser   string `json:"remindUser,omitempty"`
}

type RemindCronModel struct {
	TaskId   string        `db:"task_id"`
	CronTime time.Duration `db:"cron_time" `
	Task     string        `db:"cron_task" `
	Reciever string        `db:"cron_recv"`
}

// StoreWechatRemindCronToDb 存储微信提醒任务到数据库
func StoreWechatRemindCronToDb(remindModel *RemindCronModel) error {
	insertSql := `insert into cron (task_id, type, cron_time, cron_task, cron_recv, created_time) values (?,?,?,?,?,?)`
	_, err := wConn.Exec(insertSql,
		remindModel.TaskId,
		"微信提醒定时任务",
		remindModel.CronTime,
		remindModel.Task,
		remindModel.Reciever,
		time.Now().Format(timeConst.TimeLayoutFormat),
	)
	if err != nil {
		fmt.Println(err)
		return err
	}
	return nil
}

func StoreWechatRemindCron(remindModel *RemindCronModel) error {
	//设置定时任务
	// 存储定时任务数据到数据库
	StoreWechatRemindCronToDb(remindModel)
	// 使用 taskId 做key存入redis用作定时任务记时
	err := redis.Set(remindModel.TaskId, "", remindModel.CronTime)
	if err != nil {
		fmt.Println(err)
		return err
	}
	return nil
}

func GetCronTask(taskId string) (*RemindCronModel, error) {
	var cronTask []RemindCronModel
	sqlStr := "select task_id,cron_time,cron_task,cron_recv from cron where task_id = ? limit 1"
	err := rConn.Select(&cronTask, sqlStr, taskId)
	if err != nil {
		zap.L().Error("GetCronTask failed, err: ", zap.Error(err))
		return nil, err
	}
	if len(cronTask) > 0 {
		zap.L().Info("查询定时任务数据", zap.Any("cronTask", cronTask))
		return &cronTask[0], nil
	} else {
		return nil, fmt.Errorf("未查询到定时任务数据,taskId:%s ", taskId)
	}

}

func DeleteCronTask(taskId string) error {
	deleteSql := `delete from cron where task_id = ?`
	_, err := wConn.Exec(deleteSql, taskId)
	if err != nil {
		return err
	}
	return nil
}
